//点击表格选中前面的checkbox复选框
$(document).on("click", ".layui-table-body table.layui-table tbody tr", function () {
    var index = $(this).attr('data-index');
    var tableBox = $(this).parents('.layui-table-box');
    //存在固定列
    if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length > 0) {
        tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
    } else {
        tableDiv = tableBox.find(".layui-table-body.layui-table-main");
    }
    var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
    if (checkCell.length > 0) {
        checkCell.click();
    }
});
//对td的单击事件进行拦截停止，防止事件冒泡再次触发上述的单击事件（Table的单击行事件不会拦截，依然有效）
$(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
    e.stopPropagation();
});

// 全局 lay-tips 处理
$(document).on('mouseenter', '*[lay-tips]', function () {
    var tipText = $(this).attr('lay-tips');
    layer.tips(tipText, this, {
        tips: 1, //在上边
        time: -1 //-1不做时间限制
    });
}).on('mouseleave', '*[lay-tips]', function () {
    layer.closeAll('tips');
});

/**二维码*/
function queryQrCode(code, qrCode) {
    var qrCode = converToUtf8(qrCode);
    layer.open({
        type: 1,
        id:'qrcode_id',
        title: "<span style='color: #46a6cf;font-size:13px;font-family: 微软雅黑'>【" + code + "】二维码</span>",
        area: [324, 410],
        content: '<div style="margin: 5px 5px" id="QRCode"></div>',
        shadeClose: true,
        btn:['打印','关闭'],
        btnAlign:'c',
        //打印按钮
        btn1: function(index, layero){
            $("#qrcode_id").print();
            layer.close(index);
        },
    });
    new QRCode(document.getElementById('QRCode'), {
        text: qrCode,
        width: 309,
        height: 295,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
    });
}
function converToUtf8(input) {
    var out, i, len, c;
    out = "";
    len = input.length;
    for (i = 0; i < len; i++) {
        c = input.charCodeAt(i);
        if ((c >= 0x0001) && (c <= 0x007F)) {
            out += input.charAt(i);
        } else if (c > 0x07FF) {
            out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
            out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        } else {
            out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
            out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
        }
    }
    return out;
}

/**
 * 通用附件下载 查看
 * @param fileName
 * @param filePath
 * @param suffix
 */
function downloadAttachCommon(fileName, filePath, suffix) {
    if (!utils.string.isEmpty(filePath)) return;
    var url = fjHttp + filePath;
    if (utils.string.isEmpty(suffix)) {
        if (".pdf.PDF".indexOf(suffix) != -1) {
            viewPdfCommon(url, fileName);
        } else if (".jpg.png.bmp.jepg.gif.JPG.PNG.BMP.JEPG.GIF".indexOf(suffix) != -1) {
            viewImgCommon(url);
        } else {
            window.location.href = basePath+'/downloadFile?filePath='+filePath+'&fileName='+fileName+'&suffix='+suffix;
        }
    } else {
        var fileNameIndex = fileName.lastIndexOf(".");
        var fileNameLength = fileName.length;
        var suffix = fileName.substring(fileNameIndex + 1, fileNameLength)
        var fileNameNew = fileName.substring(0, fileNameIndex);
        if (".pdf.PDF".indexOf(suffix) != -1) {
            viewPdfCommon(url, fileNameNew);
        } else if (".jpg.png.bmp.jepg.gif.JPG.PNG.BMP.JEPG.GIF".indexOf(suffix) != -1) {
            viewImgCommon(url);
        } else {
            window.location.href = basePath+'/downloadFile?filePath='+filePath+'&fileName='+fileName;
        }
    }
}

function viewImgCommon(imgUrl) {
    var imgUrl = imgUrl;
    getImageWidthCommon(imgUrl, function (w, h) {
        w = h > 860 ? w / h * 860 : w
        h = h > 860 ? 860 : h
        parent.layer.open({
            type: 1,
            title: false,
            offset: 'auto',
            area: [w + 'px', h + 'px'],
            shadeClose: true,
            content: '<div><img style="max-width: 100%;max-height: 100%" src="' + imgUrl + '"></div>'
        });
    });
}

// 获取图片真实高度
function getImageWidthCommon(url, callback) {
    var img = new Image();
    img.src = url;
    // 如果图片被缓存，则直接返回缓存数据
    if (img.complete) {
        callback(img.width, img.height);
    } else {
        img.onload = function () {
            callback(img.width, img.height);
        }
    }
}

function viewPdfCommon(url, name) {
    layer.open({
        type: 1,
        title: name + ' 预览',
        shadeClose: true,
        skin: 'layer-ext-myskin',
        offset: '10px',
        shade: 0.3,
        area: ['95%', '95%'],
        content: '<div id="pdfPreview" style="height:100%"></div>'
    });
    PDFObject.embed(url, "#pdfPreview");
}

/*
	 * 关闭layer弹窗
	 * type--》刷新父页面
	 * id 父页面表格id
	 * */
function closeLayerIndex(type,id){
    parent.layer.close(parent.layer.getFrameIndex(window.name));//关闭当前页
    if (!isEmpty(type) && !isEmpty(id)) {
        parent.layui.table.reload(id);
    }
}

/*表单*/
function parseForm(){
    $.fn.parseForm=function(){
        let serializeObj={};
        let array=this.serializeArray();
        let str=this.serialize();
        $(array).each(function(){
            if(serializeObj[this.name]){
                if($.isArray(serializeObj[this.name])){
                    serializeObj[this.name].push(this.value);
                }else{
                    serializeObj[this.name]=[serializeObj[this.name],this.value];
                }
            }else{
                serializeObj[this.name]=this.value;
            }
        });
        return serializeObj;
    };
}

/**
 * 防止重复提交
 * @param type
 */
function checkSubBtn(type){
    // 单击之后提交按钮不可选,防止重复提交
    var DISABLED = 'layui-btn-disabled';
    if (type == 1){
        // 增加样式
        $('.subCheckBtn').addClass(DISABLED);
        // 增加属性
        $('.subCheckBtn').attr('disabled', 'disabled');
    }else if (type == 2){
        $('.subCheckBtn').removeClass(DISABLED);
        $('.subCheckBtn').removeAttr('disabled');
    }
}

//首页初始化
 function  initIndex(callback, url, data) {
     var loadIndex = null;
     sendAjaxPostToCallback(
         url,
         data,
         function (data) {
             if (data.success) {
                 callback(data);
             } else {
                 top.layui.notice.msg(data.msg ,{icon: 2,position:"topCenter"});
             }
         },
         function (data) {
             if (utils.string.isEmpty(data) && utils.string.isEmpty(data.msg)){
                 top.layui.notice.msg(data.msg ,{icon: 2,position:"topCenter"});
             }else{
                 top.layui.notice.msg("服务器内部错误，请联系管理员~", {icon: 2,position:"topCenter"});
             }
         },
         function () {
             loadIndex = layer.load(1);
         },
         function () {
             layer.close(loadIndex);
         },
     )
}
//获取字典下拉框
function initSelectData(dictCode,isDelete=0){
    var result = [];
    $.ajaxSettings.async = false;
    $.ajax({
        url: window.basePath + '/dictData/getDictDataXMSelect?dictCode='+dictCode+'&isDelete='+isDelete,
        method: 'post',
        success: function (res) {
            if (utils.string.isEmpty(res.data)){
                result = res.data;
            }
        }
    });
    $.ajaxSettings.async = true;
    return result;
}

/**
 * 选择用户
 * @param type 1 单选 2 多选
 */
function chooseUser(type,callback){
    parent.layer.open({
        type: 2,
        id:'chooseUser_id',
        skin: 'layer-ext-myskin',
        title: "选择用户",
        area: ["90%", "90%"],
        content: basePath+ '/view/system/user/chooseUser',
        shadeClose: false,
        shade: 0.3,
        btn:['选择','关闭'],
        btnAlign:'c',
        //选择按钮
        btn1: function (index, layero) {
            var body = layer.getChildFrame('body', index);
            var iframeWin = parent.window[layero.find('iframe')[0]['name']];
            var checkStatus = iframeWin.layui.table.checkStatus('userTable').data;
            if (checkStatus.length < 1){
                top.layui.notice.msg("未选择数据~" ,{icon: 2,position:"topCenter"});
                return ;
            }
            if (type == 1){
                if (checkStatus.length != 1){
                    top.layui.notice.msg("操作有误：当前操作只能单选数据，请勿多选~" ,{icon: 2,position:"topCenter"});
                    return ;
                }
            }
            callback(checkStatus);
            parent.layer.close(index);
        },
    });
}


